<template>
    <div class="upload" v-loading="loadingController"  :element-loading-text="loadingText">
        <div class="file-list" v-show="fileList.length > 0">
            <div class="file-inner" v-for="(item,index) in fileList" :key="index">
                <div>
                    <el-link @click="goDown(item)" type="primary">{{item.filename}}</el-link>
                </div>
                <div>
                    <el-button class="detbut" type="text" icon="el-icon-delete" @click="goDetele(item)">删除
                    </el-button>
                </div>
            </div>
        </div>

        <el-upload v-show="fileList.length < 1 || !fileList " class="upload-demo" :action="actionModel.upload" :data="upFileData" multiple
            :on-success="handleAvatarSuccess" :on-error="onError" :before-upload="beforeAvatarUpload" :show-file-list="false" :accept="filetype" >
            <el-button size="small" type="primary">点击上传</el-button>
            <!-- <div slot="tip" class="el-upload__tip">且不超过10M</div> -->
        </el-upload>
    </div>
</template>

<script>
import ajax from '@components/my-components/upload-s/ajax';

export default {
    props: {
        fileguid: {
            type: String,
            default: '',
        },
        isUp: {
            type: Boolean,
            default: true,
        },
        filetype: {
            type: String,
            default: '',
        },
        folder: {
            // 附件上传后存放的位置
            type: String,
            default: 'document',
        },
        onFileSelect: {
            type: [Boolean, Function],
            default: false,
        },
        limit: {
            // 最大允许上传个数
            type: Number,
            default:2,
        },
    },
    name: '',
    data() {
        return {
            //上传附带文件
            upFileData: {
                fileguid: '',
                // filetype: '',
                single: 1,
            },
            fileList: [],

            // 附件加载进度
            loadingController: false,
            loadingText: '附件内容更新中',
            loadingBarShowController: false,
            // 大文件分包大小
            chunkSize: 5 * 1024 * 1024,
            // 防抖弹窗集合
            debounceDialogs: {},
            // 上传成功的暂存文件
            successCache: [],
        };
    },
    mounted() {},
    watch: {
        fileguid: {
            handler(n) {
                this.upFileData.fileguid = n;
                this.getAccessory(n);
            },
            deep: true,
            immediate: true,
        },
    },
    computed: {
        actionModel() {
            return {
                upload: `${this.$store.state.api.webUrl}/tbfaupload/${this.folder}/common.json`,
                del: `${this.$store.state.api.webUrl}/tbfaupload/deletefile.json`,
                list: `${this.$store.state.api.sysUrl}/operate/getlist.json`,

                uploadL: `${this.$store.state.api.fileUrl}/upload/${this.folder}/bigfileup.json`,
                download: `${this.$store.state.api.fileUrl}/download/common.do`,
                preview: `${this.$store.state.api.fileUrl}/open/look.do`,
            };
        },
        exist() {
            return this.fileList.length > 0;
        },
    },
    methods: {
        // 获取附件列表
        getAccessory(fileguid) {
            if (!fileguid) return;
            if (this.loadingController) return;
            this.loadingShow('附件内容更新中');

            let data = {
                fileguid: this.fileguid,
            };
            this.$get(this.actionModel.list, data, (data) => {
                this.fileList = data || [];
                this.loadingHide();
            });
        },
        loadingShow(text) {
            this.loadingController = true;
            this.loadingText = text || '';
        },
        //  移除loading
        loadingHide() {
            this.loadingController = false;
            this.loadingText = '附件内容更新中';
        },

        goDown(val) {
            var search = toSearch({
                rowguid: val.rowguid
            });
            downloader(`${this.$store.state.api.webUrl}/tbfaupload/common.do${search}`);
        },

        // 提交成功
        handleAvatarSuccess(res, file) {
            this.loadingHide();
            if(res.code == 'error'){
                showMsgBox(res.msg, 'error');
                return;
            }

            this.$notify({
                message: '添加成功',
                type: 'success',
            });
            this.getAccessory(this.fileguid);
        },
       
        // 上传错误  err, file, fileList
        onError: function (err) {
            this.loadingHide();
            showMsgBox(err, 'error');
        },

        // 提交前限制 文件按大小
        beforeAvatarUpload(file) {
            const isLt2M = file.size / 1024 / 1024 < 20;
            if (!isLt2M) {
                this.$message.error('上传附件大小不能超过 20MB!');
            } else{
                this.loadingShow('附件上传中');
            }
            return isLt2M;
        },
        beforeAvatarUpload2: function (file) {
            var arr = file.name.split('.'),
                type = arr[arr.length - 1], //从最后一个点开始判断文件类型
                size = file.size / 1024 / 1024,
                fs = this.filesize;

            if (this.onFileSelect) {
                this.onFileSelect(file);
            }

            return new Promise((resolve, reject) => {
                this.$nextTick(() => {
                    new Chain()
                        .link((next) => {
                            // 文件类型判断
                            if (this.filetype) {
                                var typeArr = this.filetype.split(',');

                                if (
                                    !typeArr.some(function (item) {
                                        return new RegExp(type, 'i').test(item);
                                    })
                                ) {
                                    this.debounceDialogs.filetype();

                                    return reject();
                                }

                                next();
                            } else {
                                next();
                            }
                        })
                        .link((next) => {
                            // 文件数量判断
                            if (this.limit && this.fileList.length + this.uploaderInnerFiles > this.limit) {
                                this.debounceDialogs.limit();

                                return reject();
                            }

                            next();
                        })
                        .link((next) => {
                            // 文件大小判断
                            if (fs && size > fs) {
                                this.debounceDialogs.filesize();
                                return reject();
                            }

                            next();
                        })
                        .link((next) => {
                            // 执行上传
                            return resolve();
                        })
                        .run();
                });
            });
        },

        // 删除单个文件
        goDetele(user) {
            showConfirm('删除附件后无法撤销，请确认是否删除', 'warning', () => {
                let data = {
                    rowguid: user.rowguid,
                };
                this.$post(this.actionModel.del, data, (data) => {
                    showMsg('删除成功', 'success');
                    // msg: "成功"
                    this.getAccessory(this.fileguid);
                    this.$emit('setCoverguid')
                });
            });
        },
    },
};
</script>

<style lang="scss" scoped>
.file-list {
    width: 100%;
    .file-inner {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;
        // background: pink;
        // align-items: ;
        // div {
        //     display: inline-block;
        // }
    }
}
.upload {
    width: 100%;
}
.borTop1 {
    margin-top: 20px;
}

.borTop2 {
    margin-top: 0px;
}
</style>

